package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
public class OrderCheckHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;

    @Override
    public void process(String jsonMsg) throws IOException {
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        if (StringUtils.isEmpty(orderCheck.getOrderNo())) {
            throw new LogicException("订单支付状态检查传参错误");
        }
        //查询创建状态的订单
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getOrderNo,orderCheck.getOrderNo())
                .eq(OrderEntity::getStatus, VMSystem.ORDER_STATUS_CREATE);
        OrderEntity orderEntity = orderService.getOne(wrapper);
        if (orderEntity == null) {
            throw new LogicException("订单支付状态检查,没有创建状态订单");
        }

        //订单未支付,修改订单状态为失效
        orderEntity.setStatus(VMSystem.ORDER_STATUS_INVALID);
        orderService.updateById(orderEntity);

    }
}
